package com.zhuangjie.rider.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zhuangjie.base.entity.DateTimeRange;
import com.zhuangjie.rider.service.RiderMoneyRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class RiderJob {

    @Autowired
    private RiderMoneyRecordService riderMoneyRecordService;

    private static final int BATCH_COUNT = 20;

    private static final long BATCH_INTERVAL = 100;

    /**
     * 附加订单会计记录处理程序
     * 分片+参数
     */
    @XxlJob("riderOrderAccountingRecordHandler")
    public void riderOrderAccountingRecordHandler() throws InterruptedException {
        // 分片序号
        int shardIndex = XxlJobHelper.getShardIndex();
        // 分片总数
        int shardTotal = XxlJobHelper.getShardTotal();
        // 每次处理最多数量
        Integer maxCount = Integer.valueOf(XxlJobHelper.getJobParam());
        if (maxCount == null) maxCount = 1024;
        DateTimeRange processDateTimeRange =  getProcessDateTimeRange(shardTotal,shardIndex);
        // 查询并进行到账
        List<Long> dueBillRecordIds = riderMoneyRecordService.queryDueBillRecord(processDateTimeRange, maxCount);

        int currentCount = 0;
        for (Long dueBillRecordId : dueBillRecordIds) {
            if (currentCount != 0 && currentCount % BATCH_COUNT == 0) {
                Thread.sleep(BATCH_INTERVAL);
            }
            CompletableFuture.runAsync(()->riderMoneyRecordService.moneyRecordAccounting(dueBillRecordId));
            currentCount++;
        }
    }

    public static DateTimeRange getProcessDateTimeRange(int shardTotal, int shardIndex) {
        // 获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 计算昨天的当前时间
        LocalDateTime yesterdayDateTime = currentDateTime.minusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);

        // 计算每份的时间间隔
        long totalMinutesInDay = ChronoUnit.MINUTES.between(yesterdayDateTime, currentDateTime);
        long minutesPerShard = totalMinutesInDay / shardTotal;

        // 计算开始时间
        LocalDateTime startDateTime = shardIndex == 0 ? null : yesterdayDateTime.plusMinutes(minutesPerShard * shardIndex);

        // 计算结束时间（最后一份没有结束时间）
        LocalDateTime endDateTime = shardIndex == shardTotal - 1 ? null : yesterdayDateTime.plusMinutes(minutesPerShard * (shardIndex + 1));

        return new DateTimeRange(startDateTime, endDateTime);
    }

//    public static void main(String[] args) {
//        DateTimeRange processDateTimeRange = getProcessDateTimeRange(1, 0);
//        System.out.println(processDateTimeRange);
//    }



}
